var sbold = /<b>/gi;
var ebold = /<\/b>/gi;
var currobj_id;
var load = false;

var xmlhttp;
var response = '';
var sep = ',';
var currentid;
var succ = 1;
var ncotsotienvn_input = 1;
var ncotsotiennt_input = 2;
var ncotsotiennt = 5;
var ncottygia = 6;
var nhapngoaite = 0;
var ndongbd = 2;
var SODONGCT = 5;
var addmode ;
var FormCT = "";

$(document).ready(function() {
	$('.tabs .tab-links a').click(function(e){
        var currentAttrValue = $(this).attr('href');
       $('.tabs ' + currentAttrValue).show().siblings().hide();
	   if (FormCT == "")
	   {
			FormCT = "Thue"
			$('a#tab1').css("color", "MidnightBlue");
			$('a#tab2').css("color", "red");
	   }
	   else{
		   FormCT = "";
			$('a#tab2').css("color", "MidnightBlue");
			$('a#tab1').css("color", "red");
	   }
       //$(this).parent('td').parent('li').addClass('active').siblings().removeClass('active');
        //e.preventDefault();
    });

	$('.datepicker').each(function() {
		$(this).removeClass('hasDatepicker').datepicker({dateFormat:"dd/mm/yy"});
	});


	$("#ngct").datepicker({dateFormat:"dd/mm/yy"});
	$("#ngaylapct").datepicker({dateFormat:"dd/mm/yy"});
	$("#ngayctcn").datepicker({dateFormat:"dd/mm/yy"});


	$('.selectMenu2').css("width", "200px");
	$('.selectMenu3').css("width", "300px");

	$('#breadcrumb').css("font-size", "1em");

	$('a#CNTMTG').click(function(){
	url = $(this).attr("href");
		var ChiTiet=document.getElementById('ttChiTiet').innerHTML;
		var LoaiTien=document.getElementById('ttLoaiTien').innerHTML;
		var Nam=document.getElementById('ttNam').innerHTML;
		url = url + "?ChiTiet="+ChiTiet+"&&Nam="+Nam+"&&LoaiTien="+LoaiTien;
		$(this).attr('href',url);
	});


	$('input#tim').click(function(){
		$('div#tim').show();
		//url = $('a#CNTMTG').attr("href");
		//alert(url);

	});

	$('input#Tim_btnOK').click(function(){
		$('div#tim').show();
		url = $('a#CNTMTG').attr("href");
		url = url.replace("/index/CN_TMTG", "/acctCN/getdsidphieu");
		ngay1= $('#tim_ngct1').val();
		var dt1   = parseInt(ngay1.substring(0,2));
		var mon1  = parseInt(ngay1.substring(3,5));
		var yr1   = parseInt(ngay1.substring(6,10));
		ngay1 = yr1+"-"+ mon1+"-" + dt1;

		ngay2= $('#tim_ngct2').val();
		var dt2   = parseInt(ngay2.substring(0,2));
		var mon2  = parseInt(ngay2.substring(3,5));
		var yr2   = parseInt(ngay2.substring(6,10));
		ngay2 = yr2+"-"+ mon2+"-" + dt2;
		if (ngay1 >ngay2)
		{
			alert("Khoảng thời gian tìm chưa hợp lý!");
			document.getElementById('tim_ngct1').focus();
			return;

		}

		if (yr1 != yr2)
		{
			alert("Chỉ tìm trong 1 năm!");
			document.getElementById('tim_ngct1').focus();
			return;
		}

		var ChiTiet=$('#ttChiTiet').html();
	
		jQuery.ajax({
		   type: "POST",
		   url: url,
		   data: {ngay1:ngay1, ngay2: ngay2, ChiTiet: ChiTiet, Year: yr1},
		   cache: false,
		   success: function(response)
		   {
			$("#list").html(response);
			$("#list").show();
		   },
		   error: function(data, errorThrown)
		  {
			  alert('request failed :'+errorThrown);
		  }
		 });
	});

	$('input#Tim_btnCancel').click(function(){
		$("div#list").hide();
		$("div#tim").hide();

	});



	$('input#edit').click(function(){
		editmode = $('input#edit').val();
		action = $('div#action').html();
		addmode = 'edit';
		//idphieu = $('div#idphieu').html();
		if (action.indexOf("Thêm") >= 0){   // dang ở chế độ thêm mới, thôi k0 thêm nữa
			 LoadCT(0,'', 2); // lay ct cuoi cung - auto cac muc khac
		}else if (action.indexOf("Xem") >=0){  // dang o chê đô xem, chuyển qua sửa
			ChangeTT("Sửa");
		}
		else   // dang o chdo sua, thoi khong sưa nua
		{
			ChangeTT("Xem");
		}
		return;
	});

	$('input#xoa').click(function(){
		if (!(confirm("Bạn muốn xóa chứng từ này không?")))
		{
			return;
		}
		idphieu = $('div#idphieu').html();
		Year = $('div#ttNam').html();
		url = $('a#CNTMTG').attr("href");
		url = url.replace("/index/CN_TMTG", "/acctCN/delect");

		jQuery.ajax({
		   type: "POST",
		   url: url,
		   data: {ChiTiet: ChiTiet, Year: Year, idphieu: idphieu},
		   cache: false,
		   success: function(response)
		   {
			   LoadCT('0','', 2);
		   },
		   error: function(data, errorThrown)
		  {
			  alert('request failed :'+errorThrown);
		  }
		 });
	});


	$('input#Tim_btnOK').click(function(){
		$('div#tim').show();
	});


	$('input#cancel').click(function(){
		url = $('a#CNTMTG').attr("href");
		url = url.replace("/index/CN_TMTG", "/index/CN_TMTG");
		var ChiTiet=document.getElementById('ttChiTiet').innerHTML;
		var LoaiTien=document.getElementById('ttLoaiTien').innerHTML;
		var Nam=document.getElementById('ttNam').innerHTML;
		url = url + "?ChiTiet="+ChiTiet+"&&Nam="+Nam;
		location.href = url;

	});


	
	$('input#timnoidung').click(function(){
		url = $('a#CNTMTG').attr("href");
		url = url.replace("/index/CN_TMTG", "/acctCN/tracuu");
		danhmuc = $('div#danhmuc').html();
		if (!danhmuc)
		{
			danhmuc = "dmtk";
		} 
		noidungtim = ($('input#noidungtim').val()).trim();
		if (noidungtim == "")
		{
			alert("Hãy nhập nội dung tìm!");
			$('input#noidungtim').focus();
			return;
		}

		jQuery.ajax({
		   type: "POST",
		   url: url,
		   data: {danhmuc: danhmuc, noidungtim: noidungtim},
		   cache: false,
		   success: function(response)
		   {
			   $('div#danhmuckq').html(response);
			   //alert("kq:" + response);
		   },
		   error: function(data, errorThrown)
		  {
			  alert('request failed :'+errorThrown);
		  }
		 });
	});

	$('input#timnoidungcancel').click(function(){
		$('div#danhmuckq').html("");
	$('div#tracuu').hide();
	});


	//$("table#mymain").css("background-color", "#D1E5EB");
	//$("table#head td").css("background-color", "LightGoldenRodYellow");

	//$("table#mymain").css("border", "1px dotted #6E7FC9");
	//$("table#mymain td").css("border", "1px dotted black");
	//$("table#myDetail td").css("border", "1px dotted #6E7FC9");
	$("td.value").css("text-align", "left");


	//$("table#myDetail").css("border", "1px solid #6E7FC9");
	//$("table#myDetail th").css("background-color", "Silver ");
	//$("table#myDetail th").css("color", "RoyalBlue");

	//$("th").css("border", "1px dotted #6E7FC9");

	//$("table#myTotal").css("border", "1px solid black");
	$("table#myTotal td").css("border", "1px solid white");

	//$('.actiondelrow').css("font-size", "0.8em");

	$('.css_corner').css("border-radius", "15px");
	$('.css_corner').css("-moz-border-radius", "21px");
	$('.css_corner').css("-webkit-border-radius", "21px");
	$('.css_corner').css("border", "thin solid #DDDDD0");
	$('.css_corner').css("text-align", "center");
	//$('.css_corner').css("background-color", "#D1E5EB");
	$('.css_corner').css("color", "#9C4147");
	$('.css_corner').css("font-size", "0.8em");


	//$('.title').css("font-family", "ABeeZee") ;
	//$('.title').css("line-height", "1em") ;
	//$('.title').css("font-size", "2em") ;
	//$('.title').css("color", "#458B74") ;
	//$('.title').css("text-shadow", "4px 2px 4px #C2C2C2") ;


	
	$( "#ngctcn1" ).datepicker({dateFormat:"dd/mm/yy"});
	$( "#ngctcn2" ).datepicker({dateFormat:"dd/mm/yy"});
	$( "#ngctcn" ).datepicker({dateFormat:"dd/mm/yy"});
	$( "#fNgay1" ).datepicker({dateFormat:"dd/mm/yy"});
	$( "#fNgay2" ).datepicker({dateFormat:"dd/mm/yy"});
	$( ".datepicker" ).datepicker({dateFormat:"dd/mm/yy"});
	


	$("input").keydown(function(){
		//alert(event.keyCode );
		var self = $(this)
		  , form = self.parents('form:eq(0)')
		  , focusable
		  , next
		  ;
		if (event.keyCode == 13) {
			focusable = form.find('input').filter(':text');
			next = focusable.eq(focusable.index(this)+1);
			if (next.length) {
				//alert(event.keyCode );
				next.focus();
			} else {
			}
			return false;
		}

		
	});
	
	var validator = $("#CTTMTG").validate();
	jQuery("#isstate").blur(function() {

		var states = ['PA', "CA"] // of course you will need to add more
		var in_array = $.inArray(value.toUpperCase(), states);
		if (in_array == -1) {
			return false;
		}else{
			return true;
		}
	});

	jQuery.validator.addMethod('integer', function (value, element, param) {
        return (value != 0) && (value == parseFloat(value, 10));
    }, 'Please enter a non zero integer value!');

	 
});

function DMTraCuu()
{
}

function ChonDM(ma)
{
	eleid = $('div#eleid').html();
	$('select#'+ eleid).val("_"+ma);
	$('div#danhmuckq').html("");
	$('div#tracuu').hide();
}

function ChangeTT(TrangThai){
	if (TrangThai == "Xem")   //chuyen sang TT xem
	{
		$('input#save').attr("value", "Thêm mới");
		$('input#edit').attr("value", "Sửa");
		$('input#print').attr("disabled", false);
		$('input#xoa').attr("disabled", false);
		$('div#action').html("Xem chứng từ");
		$('div#ctlinks').show();

	} else if (TrangThai == "Sửa")   // Chuyen sang TT sưa
	{

		$('input#save').attr("value", "Ghi lại");
		$('input#edit').attr("value", "Thôi sửa");
		$('div#action').html("Sửa chứng từ");
		$('input#print').attr("disabled", true);
		$('input#xoa').attr("disabled", true);
		$('input#soct').focus();
		addmode = "edit";
	}
	else{ // Chuyển sang TT thêm
		 $('input#print').attr("disabled", true);
		 $('input#save').attr("value", "Ghi lại");
		 $('input#edit').attr("value", "Thôi");
		 $('div#action').html("Thêm chứng từ mới");
		$('input#print').attr("disabled", true);
		$('input#xoa').attr("disabled", true);

		 $('div#ctlinks').hide();
 		 addmode = "add";
	}
}


function LoadCT(idphieu, chon, linkdirect){
	// Load lại 1 ctừ theo idphieu
	//linkdirect = 1; //next ... -1, +1, 0, 2
	ChangeTT("Xem");
	if (chon != 'chon') // neu chon tu ket qua tim 
	{
		$('div#tim').hide();
		$('div#list').hide();

	}

	urlg = $('a#CNTMTG').attr("href");
	url = urlg.replace("/index/CN_TMTG", "/acctCN/getct")
	Year = $('div#ttNam').html();
	ChiTiet=$('#ttChiTiet').html();  // mact

	jQuery.ajax({
	   type: "POST",
	   url: url,
	   data: {idphieu: idphieu, ChiTiet: ChiTiet, Year: Year, linkdirect: linkdirect},
	   cache: false,
	   success: function(response)
	   {
			giatri = response.split(":::::");
			$("div#ctlinks").html(giatri[0]);
			$("div#Main").html(giatri[1]);
			$("div#tab1").html(giatri[2]);
			$("div#tab2").html(giatri[3]);  // newv
			if ($('select#mant').val() == "VND")
			 {
				 hideusd();
			 }
			 else
			 {
				 showusd();
			 }

			gettotal();
			$("input#soct").focus();


	   },
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
	 });

}

function gettotal(){
	var total = 0; totalnt = 0;
	var i1=0; st=0;

	var x=document.getElementById('myDetail');
	var sdong = x.rows.length ; 
	$('input[id^="sotienvn"]').each(function(i1){
		st = $(this).val();
		st = parseFloat(st.replace(/,/g, ""));
		if (st >0 )
		{
			total +=  st;
		}
	});
	var mant = $('#mant').val();
	if (mant == 'VND')
	{
		document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ"; 
	}
	else{
		document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")"; 
	}



	return;

	var id= "sotienvn";
	st = $("input#"+id).val();
	alert('gettotal'+ st);

	st = parseFloat(st.replace(/,/g, ""));
	if (st >0 )
	{
		total +=  st;
	}

	var mant = $('#mant').val();
	if (mant == 'VND')
	{
		document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ"; 
	}
	else{
		document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")"; 

	}
	return;
	var ncotvn = 3;
	var ncotnt = 4 ;
	var input ;
	var new_row ;
	var inp1 ;

	for (i1 =0 ; i1< sdong ; i1++){
	    new_row = x.rows[ndongbd+i1];
		input = new_row.getElementsByTagName('input');
		inp1 = input[ncotvn];
		st = $("#"+inp1.id).val();
		st = parseFloat(st.replace(/,/g, ""));
		if (st >0 )
		{
			total +=  st;
		}
		inp1 = input[ncotnt];
		st = $("#"+inp1.id).val();
		st = parseFloat(st.replace(/,/g, ""));
		if (st >0 )
		{
			totalnt +=  st;
		}
	}
	var mant = $('#mant').val();
	if (mant == 'VND')
	{
		document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ"; 
	}
	else{
		document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")"; 

	}

	return;
	}

function getctfirst(){
	year = $('div#ttNam').html();
	ChiTiet=$('#ttChiTiet').html();  // mact

	url = $('a#CNTMTG').attr("href");
	url = url.replace("/index/CN_TMTG", "/acctCN/getminidphieu")
	var minidphieu; 
	jQuery.ajax({
	   type: "POST",
	   url: url,
	   data: {year:year, ChiTiet:ChiTiet},
	   cache: false,
	   success: function(response)
	   {
		   minidphieu = response;
		   LoadCT(minidphieu);
		
	   },
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
	 });
}

function getctlast(){
	year = $('div#ttNam').html();
	ChiTiet=$('#ttChiTiet').html();  // mact

	url = $('a#CNTMTG').attr("href");
	url = url.replace("/index/CN_TMTG", "/acctCN/getmaxidphieu")
	var minidphieu; 
	jQuery.ajax({
	   type: "POST",
	   url: url,
	   data: {year:year, ChiTiet:ChiTiet},
	   cache: false,
	   success: function(response)
	   {
		   midphieu = response;
		   LoadCT(midphieu);
	   },
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
	 });
}

function getctprev(){
	year = $('div#ttNam').html();
	ChiTiet=$('#ttChiTiet').html();  // mact
	idphieu = $('div#idphieu').html();

	url = $('a#CNTMTG').attr("href");
	url = url.replace("/index/CN_TMTG", "/acctCN/getprevidphieu")
	var midphieu; 
	// lay idphieu cuoi cung
	jQuery.ajax({
	   type: "POST",
	   url: url,
	   data: {year:year, ChiTiet:ChiTiet, idphieu: idphieu},
	   cache: false,
	   success: function(response)
	   {
		   midphieu = response;
		   LoadCT(midphieu);
	   },
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
	 });
}

function getctnext(){
	year = $('div#ttNam').html();
	ChiTiet=$('#ttChiTiet').html();  // mact
	idphieu = $('div#idphieu').html();

	url = $('a#CNTMTG').attr("href");
	url = url.replace("/index/CN_TMTG", "/acctCN/getnextidphieu")
	var midphieu; 
	jQuery.ajax({
	   type: "POST",
	   url: url,
	   data: {year:year, ChiTiet:ChiTiet, idphieu: idphieu},
	   cache: false,
	   success: function(response)
	   {
		   midphieu = response;
		   LoadCT(midphieu);
	   },
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
	 });
}

function LoadForm_add(sdong){
	//newv 07-02-2015
	$('div#idphieu').html("");
	//newv 07-02-2015--end
	for (iL= 1; iL<sdong; iL++)
	{
		addnewrow_add();
	}
	document.getElementById("soct").focus();
	hideusd();
	$('#ctlinks').hide();
	var ModeList = $('div#ModeList').html();
	if (ModeList  == 1)
	{
			$('div#tim').show();
			$('div#list').show();
			$('div#editct').hide();
			$('input:button').attr("disabled", true);
	} else{
		document.getElementById("soct").focus();
	}
}

function showusd(){
	var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncotsotiennt+'), #myDetail td:nth-child('+ncotsotiennt+')');
	tags.show();

	var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncottygia+'), #myDetail td:nth-child('+ncottygia+')');
	tags.show();
	nhapngoaite = 1;
}

function hideusd(){
	var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncotsotiennt+'), #myDetail td:nth-child('+ncotsotiennt+')');
	tags.hide();

	var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncottygia+'), #myDetail td:nth-child('+ncottygia+')');
	tags.hide();
	nhapngoaite  = 0;

}

function changeMaNT(id){
	var mant = $('#'+ id).val();
	if (mant == "VND")
	{
		hideusd();
	}
	else{
		showusd();
	}
	tinhtong();
}

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    if (arr[i] !== undefined) rv[i] = arr[i];
  return rv;
}


function LoadForm_edit(sdong, matk, mant, tkduss, macttkduss, sotienvnss, sotienntss, diengiaiss, urlGettendmTK,urlGettendmDV ){
	//NewV------------- 
	var ModeList = $('div#ModeList').html();
	if (ModeList  == 1)
	{
			$('div#tim').show();
			$('div#list').show();
	} else{
		document.getElementById("soct").focus();
	}
	if ($('select#mant').val() == "VND")
	 {
		 hideusd();
	 }
	 else
	 {
		 showusd();
	 }
	ChangeTT("Xem");

	return;
	//NewV--------------End



	$('div#action').html("Xem chứng từ");
	$('input#save').attr("value", "Thêm mới");
	$('input#edit').attr("disabled", false);



	var myObject = {};
	if (mant == "VND")
	{
		hideusd();
	}

	for (iL= 1; iL<sdong; iL++)
	{
		addnewrow_add();
	}

	//$('body').css("font-size", "0.8em");
    $('input#print').attr("disabled", false);
	tkdus = tkduss.split(",,,");
	macttkdus = macttkduss.split(",,,");
	sotienvns = sotienvnss.split(",,,");
	sotiennts = sotienntss.split(",,,");
	diengiais = diengiaiss.split(",,,");
	
	myObject.tkdus = toObject(tkdus);
	myObject.macttkdus = toObject(macttkdus);
	myObject.sotienvns = toObject(sotienvns);
	myObject.sotiennts = toObject(sotiennts);
	myObject.diengiais = toObject(diengiais);


	fieldstring = "tkdu -  macttkdu - sotienvn - sotiennt - diengiai "; 
	//fieldstring = "tkdu -  macttkdu - sotienvn";


	var x=document.getElementById('myDetail');

	cot = 0;
	var dataCT = Array();
	var fieldCT = Array();

	$(".myheaderrow").each(function(i, v){
		$(this).find('th#select').each(function(ii, vv){
			fieldCT[cot] = $(this).attr("name");
			dataCT[cot] = Array();
			if (fieldstring.indexOf(fieldCT[cot]) >=0){
				dataCT[cot] = Array();
				for (i1 =0 ; i1< sdong ; i1++){
					name = fieldCT[cot]+'s';
					dataCT[cot][i1] = "_"+ myObject[name][i1] ;
					//dataCT[cot][i1] = "_"+  eval(fieldCT[cot]+'s['+i1+']');			
				}
			}else{
				//alert(fieldCT[cot] + " chưa cập nhật!");
				for (i1 =0 ; i1< sdong ; i1++){
					dataCT[cot][i1] = "";
				}
			}
			cot = cot+1;
		}); 

		$(this).find('th#input').each(function(ii, vv){
			fieldCT[cot] = $(this).attr("name");
			dataCT[cot] = Array();
			if (fieldstring.indexOf(fieldCT[cot]) >=0)
			{
				for (i1 =0 ; i1< sdong ; i1++){
					name = fieldCT[cot]+'s';
					dataCT[cot][i1] = myObject[name][i1] ;
					if (fieldCT[cot].indexOf("sotien") ==0){
						dataCT[cot][i1] = addCommas(dataCT[cot][i1] );
					}
				}
			}
			else{
				//alert(fieldCT[cot] + " chưa cập nhật!!!");
				for (i1 = 0 ; i1< sdong ; i1++ ){
					dataCT[cot][i1] = "";
				}
			}
			cot = cot + 1;
		}); 
	});
	var ncotvn = 3;
	var ncotnt = 4 ;
	var total = 0; totalnt = 0;


	for (i1 =0 ; i1< sdong ; i1++){
	    var new_row = x.rows[ndongbd+i1];
		var sele = new_row.getElementsByTagName('select');
		var input = new_row.getElementsByTagName('input');
		var div = new_row.getElementsByTagName('div');
		var cot = 0;

		for (i = 0 ; i< sele.length; i++){
			var sele1 = sele[i];
			$("#"+sele1.id).val(dataCT[cot][i1]);
			cot = cot +1;
		}
		var sele1 = sele[0];
		changeMa(sele1.id, urlGettendmTK);
		var sele1 = sele[1];
		changeMaCTTK(sele1.id, urlGettendmDV);

		for (i = 0 ; i< input.length; i++){
			var inp1 = input[i];
			$("#"+inp1.id).val(dataCT[cot][i1]);
			if (cot == ncotvn)
			{
				var st = parseFloat((dataCT[cot][i1]).replace(/,/g, ""));
				if (st >0 )
				{
					total +=  st;
				}
			}

			if (cot == ncotnt)
			{
				var stnt = parseFloat((dataCT[cot][i1]).replace(/,/g, ""))*100000;
				if (stnt >0 )
				{
					totalnt +=  stnt;
				}
			}

			cot = cot + 1;
		}
	}

	if (mant == 'VND')
	{
		document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ"; 
	}
	else{
		document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")"; 

	}

	return;
}

function jgetDV(pkq, url)
{
	if (currobj_id.indexOf('chitiettkdu')==0)
	{
		pmadv = pkq.split('::');
		pma = pmadv[0];
		$("#" + currobj_id).val(pma);
		HideDM();
		changeMaCTTK(currobj_id, url);
	}
	return;
}


function RefeshDM()
{	var e = document.getElementById("DM");
	var ma = e.options[e.selectedIndex].value;
	if (ma == 0)
	{
		document.getElementById('danhmucTK').style.display = 'none';
		document.getElementById('danhmucDV').style.display = 'block';
	}
	else if (ma == 1)
	{
		document.getElementById('danhmucTK').style.display = 'block';
		document.getElementById('danhmucDV').style.display = 'none';

	}
}


function zRefeshDM(danhmucs, tendm)
	{
		danhmuc = danhmucs.split(",,,,,");
		document.getElementById('danhmuc').innerHTML  = "<b>"+tendm+"</b><br>";
		for (i = 0; i < danhmuc.length ; ++i) 
		{ 
			document.getElementById('danhmuc').innerHTML  = document.getElementById('danhmuc').innerHTML + "<br>"+ danhmuc[i];
		}
		document.getElementById('danhmuc').innerHTML  = document.getElementById('danhmuc').innerHTML + "<br>";

	}

function refreshDMDV(letter, url)
{
	url = url+ "?dmdv_initial="+ letter;
	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   //alert(response);
		   document.getElementById('danhmucDV_ND').innerHTML = "Các Đơn vị bắt đầu là <b>" + letter+ "</b>:<br>(Nhấn CRL+F để tìm kiếm)<hr>"+ response;
		   
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });


}


function jgetTK(pkq, url)
{
	//alert(pkq+ url+ currobj_id);
	if (currobj_id.indexOf('tkdu')==0)
	{

		pma = pkq.split('::');
		pma = pma[0];
		$("#" + currobj_id).val(pma);
		HideDM();
		changeMa(currobj_id, url);
	}
	return;
}

function jgetmaTK(pma, pten)
{
	if (currobj_id.indexOf('tkdu')==0)
	{
		var dd = document.getElementById(currobj_id);
		for (var i = 0; i < dd.options.length; i++) {
			if (dd.options[i].text === pma) {
				dd.selectedIndex = i;
				break;
			}
		}
		// lay ra ten 
		var x= dd.parentNode;
		var a = x.getElementsByTagName('div')[0];
		a.innerHTML = pten;
	}

}


function jgetmaDV(pma, pten)
{
	if (currobj_id.indexOf('chitiettkdu')==0)
	{
		var dd = document.getElementById(currobj_id);
		for (var i = 0; i < dd.options.length; i++) {
			if (dd.options[i].text === pma) {
				dd.selectedIndex = i;
				break;
			}
		}
		// lay ra ten 
		var x= dd.parentNode;
		var a = x.getElementsByTagName('div')[0];
		a.innerHTML = pten;
	}

}


function SetCur(pObj, tkdvs, tkcps)
{
	currobj_id = pObj
	return;

	if (currobj_id.indexOf('tkdu')==0)
	{
		document.getElementById('danhmucTK').style.display = 'block';
		document.getElementById('danhmucDV').style.display = 'none';
	}
	else if (currobj_id.indexOf('chitiettkdu')==0)
	{
		idmatk = currobj_id.replace("chitiettkdu", "tkdu");
		matk = document.getElementById(idmatk).value;
		if (matk.length == 0 )
		{
			alert("Ban chua nhap MATK!" );
			document.getElementById(idmatk).focus();
			return;
		}
		p = tkdvs.indexOf(matk+"-"); 

		if (p=0 || tkdvs.substr(p-1,1) == '-')
		{

			document.getElementById('danhmucTK').style.display = 'none';
			document.getElementById('danhmucDV').style.display = 'block';
		}
		else
		{
			document.getElementById('danhmucTK').style.display = 'none';
			document.getElementById('danhmucDV').style.display = 'none';


		}
	}
	else
	{
		document.getElementById('danhmucTK').style.display = 'none';
		document.getElementById('danhmucDV').style.display = 'none';
	}


}



function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
	//alert(charCode);
	if (charCode == 46 )
	{
		return true;
	}
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}    


function EnterMa(id, idHint, aData)
{
	var stk, astk, pos;
	var kq = document.getElementById(id).value.toUpperCase();
	dmtk = aData.split(",");
	
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toUpperCase();
		pos = stk.indexOf(kq);
		if (pos==0)
		{
			astk = stk.split("-");
			document.getElementById(idHint).innerHTML  =  astk[1];
			return;
		}
	}
	document.getElementById(idHint).innerHTML  =  "*M&#227; nh&#7853;p sai ";
}


function close_window() {
  if (confirm("Ban muon ngung cap nhat?")) {
    close();
  }
}



function OnBlurInput(aData, v)
{

	var a = aData.split(",");

	var i;
	var co = 0;
	for (i=0; i<a.length; i++) 
		{ if (a[i].indexOf(v) >=0) 
			{
			co = 1;
			break;
			}

		}

		
	if (co == 0) {
		document.forms['CTTMTG'].elements['isstate'].focus();
	}

}

function addnew() {
  // Insert a DOM element object
  $('#myDiv').load('http://localhost/duoctu3/templates/acctKT/SDTTForm_add.php');



}

 function getmaxid(){
     var x=document.getElementById('myDetail');
	 var len = x.rows.length;
 	 var a = x.getElementsByTagName('a');
	 var idbd= a[0].id;
	 var maxid ; 
	 if (a.length == 1)
	 {
		maxid = 1;
	 }
	 else{
		var idkt = a[a.length-1].id;
		maxid = idkt.replace(idbd, "");
	 	maxid = parseInt(maxid)+1;
	 }
 
	 return maxid; 
 }

 function getdong(rId){
     var x=document.getElementById('myDetail');
	 var len = x.rows.length;
 	 var a = x.getElementsByTagName('a');
		for (i=0;i<a.length ; i++)
		{
			if (rId == a[i].id)
			{
				row = i + ndongbd;
			}
		}
	 return row; 
 }


 function addnewrow_edit(tkdus, macttkdus, sotiennts, sotienvns, diengiais, sotienntss)
 {
	// alert(sotienntss);
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);
	
    var len = getmaxid();
	var ncot = new_row.cells.length;

	var sele1 = new_row.cells[0].getElementsByTagName('select')[0];
	sele1.id += len;
	
	//tkdus = "_"+tkdus;
	//$("#"+sele1.id).val("_1122"); khoong dungduoc 
	{//tkdus
		for (var i = 0; i < sele1.options.length; i++) {
			if ((sele1.options[i].text).indexOf(tkdus) == 0) {
				sele1.selectedIndex = i;
				break;
			}
		}
	}


	sele1 = new_row.cells[1].getElementsByTagName('select')[0];
	sele1.id += len;
	//$("#"+sele1.id).val("_"+macttkdus);
	{//macttkdu
		for (var i = 0; i < sele1.options.length; i++) {
			if ((sele1.options[i].text).indexOf(macttkdus) == 0) {
				sele1.selectedIndex = i;
				break;
			}
		}
	}

	var cot = 2;
	if (sotienntss !=-1)
	{
		var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
		cot = cot +1;
		input1.value = 	addCommas(sotiennts);

	}

	var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
	cot = cot +1;
	{//sotienvn
		input1.id += len;
		input1.value = addCommas(sotienvns) ;
	}

	var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
	cot = cot+1;
	{//sotienvn
		input1.id += len;
		input1.value = diengiais;
		
	}

	var a1 = new_row.getElementsByTagName('a')[0];
	a1.id += len;

	var inp1 = new_row.getElementsByTagName('div')[0];
	inp1.innerHTML= '';

	var inp1 = new_row.getElementsByTagName('div')[1];
	inp1.innerHTML= '';

    x.appendChild( new_row );
 }



function addnewrow_add()
{   
	///
	tId = "myDetail";
    var x=document.getElementById(tId);
    var new_row = x.rows[2].cloneNode(true);

    var sele = new_row.getElementsByTagName('select');
    var input = new_row.getElementsByTagName('input');
    var div = new_row.getElementsByTagName('div');
    var a = new_row.getElementsByTagName('a');
    var len = getmaxid();
	var i;
    for (i = 0 ; i< sele.length; i++){
        var sele1 = sele[i];
        sele1.id += len;
        $("#"+sele1.id).val();
    }

    for (i = 0 ; i< input.length; i++){
        var inp1 = input[i];
        inp1.id += len;
        inp1.value = '';
    }

    for (i = 0 ; i< a.length; i++){
        var a1 = a[i];
        a1.id += len;
    }

    for (i = 0 ; i< div.length; i++){
        var div1 = div[i];
        div1.innerHTML= '';

    }

    x.appendChild( new_row );
    sele1 = sele[0];
    sele1.focus();

	///
	tId = "myDetailThue";
    var x=document.getElementById(tId);
    var new_row = x.rows[2].cloneNode(true);
    var sele = new_row.getElementsByTagName('select');
    var input = new_row.getElementsByTagName('input');
    var div = new_row.getElementsByTagName('div');
    var a = new_row.getElementsByTagName('a');
    for (i = 0 ; i< sele.length; i++){
        var sele1 = sele[i];
        sele1.id += len;
        //$("#"+sele1.id).attr('selectedIndex', 0);
    }

    for (i = 0 ; i< input.length; i++){
        var inp1 = input[i];
        inp1.id += len;
        inp1.value = '';
    }

    for (i = 0 ; i< a.length; i++){
        var a1 = a[i];
        a1.id += len;
    }

    for (i = 0 ; i< div.length; i++){
        var div1 = div[i];
        div1.innerHTML= '';

    }

    x.appendChild( new_row );


	///
	$('.datepicker').each(function() {
    $(this).removeClass('hasDatepicker').datepicker({dateFormat:"dd/mm/yy"});
	});
    return;

}

 function addnewrow_addLuu()
 {
	 //alert(FormCT);""; Thue
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);
	var sele = new_row.getElementsByTagName('select');
	var input = new_row.getElementsByTagName('input');
	var div = new_row.getElementsByTagName('div');
	var a = new_row.getElementsByTagName('a');
	var len = getmaxid();


	
	for (i = 0 ; i< sele.length; i++){
		var sele1 = sele[i];
		sele1.id += len;
		$("#"+sele1.id).val();
	}

	for (i = 0 ; i< input.length; i++){
		var inp1 = input[i];
		inp1.id += len;
		inp1.value = '';
	}

	for (i = 0 ; i< a.length; i++){
		var a1 = a[i];
		a1.id += len;
	}

	for (i = 0 ; i< div.length; i++){
		var div1 = div[i];
		div1.innerHTML= '';
	}
	x.appendChild( new_row );
	sele1 = sele[0];
	sele1.focus();
	return;

	
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);

	var len = getmaxid();
	var ncot = new_row.cells.length;
	var sele1 = new_row.cells[0].getElementsByTagName('select')[0];
	sele1.id += len;
	sele1 = new_row.cells[1].getElementsByTagName('select')[0];
	sele1.id += len;

	for (i = 2 ; i< ncot - 2; i++)
	{
		var inp1 = new_row.cells[i].getElementsByTagName('input')[0];
		inp1.id += len;
		inp1.value = '';
	}
		var inp1 = new_row.cells[ncot-2].getElementsByTagName('input')[0];
		inp1.id += len;
	
	var a1 = new_row.getElementsByTagName('a')[0];
	a1.id += len;

	var inp1 = new_row.getElementsByTagName('div')[0];
	inp1.innerHTML= '';

	var inp1 = new_row.getElementsByTagName('div')[1];
	inp1.innerHTML= '';

    x.appendChild( new_row );
	sele1 = new_row.cells[0].getElementsByTagName('select')[0];
	sele1.focus();

 }




function delerow(rId,tId)
{
    var parentCell = $("#"+rId).parent('td');
    parentCell = parentCell.parent('tr');
    $(parentCell).css("background","DarkGray");

    var dong =  getdong(rId);
    if (dong == ndongbd)
    {
        alert("Khong xoa duoc!");
        $(parentCell).css("background","");
    }
    else{
        if (confirm("Ban muon xoa dong nay khong?"))
        {
			if (tId == "myDetail"){
				tId2 = "myDetailThue";
			}
			else{
				tId2 = "myDetail";
			}

            document.getElementById(tId).deleteRow(dong);
			document.getElementById(tId2).deleteRow(dong);	
            tinhtong();
        }
        else{
            $(parentCell).css("background","");}
    }
    return;
}

function delerowcu(rId)
 {
	var parentCell = $("#"+rId).parent('td');
	parentCell = parentCell.parent('tr');
	$(parentCell).css("background","DarkGray");

	var dong =  getdong(rId);
	if (dong == ndongbd)
	{
		alert("Khong xoa duoc!");
		$(parentCell).css("background","");
	}
	else{
		if (confirm("Ban muon xoa dong nay khong?"))
		{
			document.getElementById("myDetail").deleteRow(dong);
			tinhtong();
		}
		else{
		$(parentCell).css("background","");}
	}
	return;
 }


function tinhtongAll(x, dong, cotnt, cotvn, tygia)
{
	if (x==null)
	{
		x=document.getElementById('myDetail');
	}
    var len = x.rows.length;

	if (tygia!==null)
	{
		tygia = document.getElementById('tygia').value;
		tygia = parseFloat(tygia.replace(/,/g, ""));
	}
	var totalvn = 0; var totalnt = 0;

	for (i = dong ; i< len; i++)
	{
		var row = x.rows[i];
		var val = row.getElementsByTagName("input");

		if (cotnt >=0)
		{
			st = val[cotnt].value;
			stnt = parseFloat(st.replace(/,/g, ""))*100;
			if (stnt >0 )
			{
				totalnt +=  stnt;
			}
		}

		st = val[cotvn].value;
		if (tygia !== null)
		{
			stvn = stnt * tygia;
			val[cotvn].value = addCommas(stvn);

		}
		else
		{
			stvn = parseFloat(st.replace(/,/g, ""));
		}

		if (stvn >0 )
		{
			totalvn +=  stvn
		}

	}

	document.getElementById("totalNT").innerHTML = addCommas(totalnt/100); 
	document.getElementById("total").innerHTML = addCommas(totalvn); 

}



function addnewrow2()
{
rowNum =1;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#myTable').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}



function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

function zShowMATK(str)
{
loadXMLDoc("gethint.php?q="+str,function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  });
}

function zzShowMATK(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="iiiiiiii";
  return;
  }

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","http://localhost/duoctu3/classes/acct/js/gethint.php?q="+str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}


function validNgay(nStr, nid, year)
{

//	var dt1   = parseInt(nStr.substring(0,2));
//	var mon1  = parseInt(nStr.substring(3,5));
//	var yr1   = parseInt(nStr.substring(6,10));
//	var ngay = new Date(yr1, mon1-1, dt1);
//
//	if (isNaN(ngay))
//	{
//		document.getElementById(nid).focus();
//		return;
//	}

		//document.getElementById(nid).value  = addCommas(nStr);
}


function validTyGia(nStr, nid)
{
	document.getElementById(nid).value  = addCommas(nStr);
}

function validnumber(nStr, nid)
{
	nStr += '';
    x = nStr.split('.');
	if (x.length >2)
	{
		alert("Nhập số chưa đúng");
		document.getElementById(nid).focus();
		return;
	}

	document.getElementById(nid).value  = addCommas(nStr);
}


// newV : thêm phần doanh số ở form Thuế:
function validSoTienVN(nStr, nid, ncot)
{
	var st = addCommas(nStr);
	document.getElementById(nid).value  = st;
	var nidNT = nid.replace('vn', 'nt');
	var nidTG = nid.replace('sotienvn', 'tygia');
	tinhtg(nid, nidNT, nidTG);
	tinhtong();
	
	var nidDoanhso =  nid.replace('sotienvn', 'sotien_doanhso');
	$("#"+nidDoanhso).val(st);
}


function validSoTienNT(nStr, nid, ncot)
{
	// tinh lai so tien VN:
	//var st1 = parseFloat(st.replace(/,/g, ""));
	nStr += '';
    x = nStr.split('.');
	if (x.length >2)
	{
		alert("Nhập số chưa đúng");
		document.getElementById(nid).focus();
		return;
	}
	document.getElementById(nid).value  = addCommas(nStr);


	var nidVN = nid.replace('nt', 'vn');
	var nidTG = nid.replace('sotiennt', 'tygia');
	tinhtg(nidVN, nid, nidTG);
	tinhtong();
	
}

function tinhtg(nidVN, nidNT, nidTG){
	var sotienvn = document.getElementById(nidVN).value ;
	sotienvn = parseFloat(sotienvn.replace(/,/g, ""));
	var sotiennt = document.getElementById(nidNT).value ;
	sotiennt = parseFloat(sotiennt.replace(/,/g, ""));

	if (sotiennt == 0 || isNaN(sotiennt))
	{
		document.getElementById(nidTG).value  = "";
	}
	else{
		var tygia = sotienvn/sotiennt;

		document.getElementById(nidTG).value  = addCommas(tygia);
	}





}


function addCommas(nStr, nid)
{    
	if (isNaN(nStr))
	{
		return nStr;
	}
	nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1].substr(0,2) : '';
	//alert(nStr+"---"+x2);
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + sep + '$2');
    }
    return x1 + x2;
}


function tinhtongn(tId)
{
    ncot = ncotsotienvn_input;
    ncotnt = ncotsotiennt_input;
    var mant = $('#mant').val();
    mant = mant.trim();
    var x=document.getElementById(tId);
    var len = x.rows.length;
    var total = 0; totalnt = 0;
    for (i = 2 ; i< len; i++)
    {
        var row = x.rows[i];
        //var cell= row.cells;
        var val = row.getElementsByTagName("input");
        //if (val.length >3)
        {
            var st = val[ncot].value;
            var stnt = val[ncotnt].value;

            var st1 = parseFloat(st.replace(/,/g, ""));
            if (st1 >0 )
            {
                total +=  st1
            }

            stnt = parseFloat(stnt.replace(/,/g, ""))*100000;
            if (stnt >0 )
            {
                totalnt +=  stnt;
            }


        }
    }
    if (mant == 'VND')
    {
        document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ";
    }
    else{
        document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")";

    }

}

function tinhtong()
{   
	ncot = ncotsotienvn_input;
	ncotnt = ncotsotiennt_input;
	var mant = $('#mant').val();
	mant = mant.trim();
    var x=document.getElementById('myDetail');
    var len = x.rows.length;
	var total = 0; totalnt = 0;
	for (i = 2 ; i< len; i++)
	{
		var row = x.rows[i];
		//var cell= row.cells;
		var val = row.getElementsByTagName("input");
		//if (val.length >3)
		{
			var st = val[ncot].value;
			var stnt = val[ncotnt].value;

			var st1 = parseFloat(st.replace(/,/g, ""));
			if (st1 >0 )
			{
				total +=  st1
			}

			stnt = parseFloat(stnt.replace(/,/g, ""))*100000;
			if (stnt >0 )
			{
				totalnt +=  stnt;
			}


		}
	}
	if (mant == 'VND')
	{
		document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ"; 
	}
	else{
		document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")"; 

	}

}

function ShowMATK(q,dmtk)
{
	if (q.length==0)
	  { 
	  document.getElementById("txtHint").innerHTML="H&#227;y nh&#7853;p M&#227; TK";
	  return;
	  }

	var hint="";
	var nhap="";
	var stk = "";

	dmtk = dmtk.split(",");
	q=q.toLowerCase(); 
	len=q.length;
	var pos = -1;

		
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toLowerCase();
		pos = stk.indexOf(q);
		if (pos ==0)
		{
			if (hint=="")
			{
				hint = "<a onclick=\"getMATK('" + dmtk[i]+  "')"+ "\">"+dmtk[i]+"</a>";
			}
			else
			{
			hint = hint+"</br><a onclick=\"getMATK('" + dmtk[i]+  "')"+ "\">"+dmtk[i]+"</a>";
			
			}
		}
	}
	document.getElementById("txtHint").innerHTML=hint;

}

function getMATK(q)
{
	document.getElementById("matk").value=q;
	document.getElementById("txtHint").innerHTML="";

}



function ShowHint(q,aData, txtHint, txtMa, ngandong )
{
	var x=document.getElementById(txtMa);
	x = x.parentNode;
	var a = x.getElementsByTagName('div')[0];


	if (q.length==0)
	  { 
	  //document.getElementById(txtHint).innerHTML="H&#227;y nh&#7853;p M&#227; ";
	  return;
	  }

	var hint="";
	var ten = "";
	var stk = "";
	var ngandong = '&nbsp; &nbsp; &nbsp;'

	//aData = aData.replace(sbold, "");
	//aData = aData.replace(ebold, "");

	dmtk = aData.split(",");
	q=q.toLowerCase(); 
	var pos = -1;

	var nhap = "";
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toLowerCase();
		//stk = stk.replace(sbold, "");
		//stk = stk.replace(ebold, "");
		nhap = nhap+ stk;

		pos = stk.indexOf("<b>"+q);
		if (pos ==0)
		{
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
			//hint = hint+ngandong+ "<a onclick=\"getMA('" + dmtk[i]+  "','"+txtMa+"',"+ "'"+ txtHint+"')"+ "\">"+dmtk[i]+"</a>";
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}
	//alert(hint);


	if (hint=="")
	{
		for (i = 0; i < dmtk.length; ++i) 
		{ 
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}

	//document.getElementById(txtHint).innerHTML=hint;
	a.innerHTML= hint;
}



function zShowHintCTTK(q,aDataLoaiTK, aDataDV, aDataCP, txtMa, ngandong )
{
	
	var hint="";
	var ten = "";
	var stk = "";
	var ngandong = '&nbsp; &nbsp; &nbsp;'
	var idmatk, idsotienvn ;
	var idmatk_value ;


	var x=document.getElementById(txtMa);
	x = x.parentNode;
	var a = x.getElementsByTagName('div')[0];

	if (q.length==0)
	  { 
	  a.innerHTML="";

	  return;
	  }

	/// loai tai khoan:
	//lay tai khoan du:
	idmatk = txtMa.replace("chitiettkdu", "tkdu");
	idsotienvn = txtMa.replace("chitiettkdu", "sotienvn");

	idmatk_value =document.getElementById(idmatk).value;

	if (idmatk_value.length == 0)
	{
		document.getElementById(txtMa).value = "";
		document.getElementById(idmatk).focus();
		a.innerHTML= "**Mã TK kh&#244;nng &#273;&#432;&#7907;c tr&#7889;ng";
		return;
	}

	/// lay danh muc tuong ung
	alert(idmatk_value);

	dmtkLoai = aDataLoaiTK.split(",");
	var inpos = dmtkLoai.indexOf(idmatk_value+"-DV");
	if (inpos>=0)
	{
		dmtk = aDataDV.split(",");
	}
	else 
	{
		inpos = dmtkLoai.indexOf(idmatk_value+"-CP");
		if (inpos>=0)
		{
			dmtk = aDataCP.split(",");
		}
		else
		{
			document.getElementById(txtMa).value = "";
			//document.getElementById(idsotienvn).focus();
			a.innerHTML= "";
			return;

		}

	}

	q=q.toLowerCase(); 
	var pos = -1;

	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toLowerCase();
		pos = stk.indexOf(q);
		if (pos ==0)
		{
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
			//hint = hint+ngandong+ "<a onclick=\"getMA('" + dmtk[i]+  "','"+txtMa+"',"+ "'"+ txtHint+"')"+ "\">"+dmtk[i]+"</a>";
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}
	
	if (hint=="")
	{
		for (i = 0; i < dmtk.length; ++i) 
		{ 
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}

	//document.getElementById(txtHint).innerHTML=hint;
	a.innerHTML= hint;
}



function changeMaCTTK(id, url)
{

	//newv----------- 07-02-2015
	var e = document.getElementById(id);
	var ma = $("#" + id).val();
	if (ma == 1)
	{
		$('label#noidungtim').html("Tìm khách hàng: &nbsp ");
		$('input#noidungtim').val("");
		$('div#danhmuc').html("dmdv");
		$('div#eleid').html(id);
		$('div#tracuu').show();
		$('input#noidungtim').focus();
		return;
	}
	ma = ma.substring(1);
	url = url+ "?dmdv_madv="+ ma;
	x = e.parentNode;
	var a = x.getElementsByTagName('div')[0];

	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {  		
		var akq = response.split("---");
		   if (id.indexOf("mact")>=0)
		   {
		   	x = e.parentNode;
			var a = x.getElementsByTagName('div')[0];
			a.innerHTML= akq[0];
		   }
		   else{
			var odiachi = document.getElementById('diachi');
			var odaidien = document.getElementById('daidien');
			if ((odaidien.value).trim() ==""){
				odaidien.value = akq[3];
			}

			if ((odiachi.value).trim() =="")
			{
				odiachi.value = akq[2];
				document.getElementById("lydo").focus();
			}

		   }
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
}



function changeMa(id, url)
{
	//newv----------- 07-02-2015
	var e = document.getElementById(id);
	var ma = $("#" + id).val();
	if (ma == 1)
	{
		$('label#noidungtim').html("Tìm tài khoản: &nbsp ");
		$('input#noidungtim').val("");
		$('div#danhmuc').html("dmtk");
		$('div#eleid').html(id);
		$('div#tracuu').show();
		$('input#noidungtim').focus();
		return;
	}
	ma = ma.substring(1);

	url = url+ "?dmtk_matk="+ String(ma);
	x = e.parentNode;
	var a = x.getElementsByTagName('div')[0];

	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   	a.innerHTML= response;
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
}

function changeMaTQ(id, url)
{
	var e = document.getElementById(id);
	var ma = e.options[e.selectedIndex].text;
	url = url+ "?ma="+ ma;
	x = e.parentNode;
	var a = x.getElementsByTagName('div')[0];


	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   	a.innerHTML= response;
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
}

function ExitMa(id, aData)
{
	var kq = document.getElementById(id).value.toUpperCase() +"-";
	var pos = aData.indexOf(kq);

	if (pos <0 )
	{
		alert("Hay nhap ma dung!");
		document.getElementById(id).value = "";
		document.getElementById(id).focus();

	}
	else
	{
		document.getElementById(id).value = kq.substr(0,kq.length-1);
	}
}


function ExitMaCTTK(id, aDatadv, tkdvs, aDatacp, tkcps)
{
	var kq = document.getElementById(id).value.toUpperCase(); //+"-";
	kq	= kq.replace(/^\s+|\s+$/g, '');
	kq = kq +"-";
	idmatk = id.replace("chitiettkdu", "tkdu");
	matk = document.getElementById(idmatk).value;
	p = tkdvs.indexOf(matk+"-"); 

	if (p=0 || tkdvs.substr(p-1,1) == '-')   // tk loai cong no
	{
			var pos = aDatadv.indexOf(kq);
			if (pos <0 )
			{
				alert("Hay nhap ma don vi dung!");
				document.getElementById(id).value = "";
				document.getElementById(id).focus();
			}
			else
			{
				document.getElementById(id).value = kq.substr(0,kq.length-1);
			}
	}
	else 
	{
		p = tkcps.indexOf(matk+"-"); 
		if (p=0 || tkcps.substr(p-1,1) == '-')   // tk loai chi phi
		{
			var pos = aDatacp.indexOf(kq);
			if (pos <0 )
			{
				alert("Hay nhap ma chi phi dung!");
				document.getElementById(id).value = "";
				document.getElementById(id).focus();

			}
			else
			{
				document.getElementById(id).value = kq.substr(0,kq.length-1);
			}
		}
		else
		{   // tk khong chi tiet
			if (kq.length >0)
			{
				alert("Day la TK khong chi tiet");
				document.getElementById(id).value = "";

			}

		}
	}

}


function zExitMa(id, idHint, aData)
{
	var x=document.getElementById(id);
	x = x.parentNode;


	var a = x.getElementsByTagName('div')[0];
	var stk, astk, pos;
	var kq = document.getElementById(id).value.toUpperCase();
	

	//aData = aData.replace(sbold, "");
	//aData = aData.replace(ebold, "");
	dmtk = aData.split(",");
	

	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toUpperCase();
		pos = stk.indexOf(kq);
		if (pos ==0 )
		{
			astk = stk.split("-");
			document.getElementById(id).value = astk[0];
			//document.getElementById(idHint).innerHTML  =  astk[1];
			a.innerHTML  =  astk[1].toLowerCase();;
			return;
		}
	}
	alert("Hay nhap ma dung ka dsadsad");
	document.getElementById(id).value = kq;
	document.getElementById(id).focus();
	//document.getElementById(idHint).innerHTML  =  "Hay nhap ma dung";
	a.innerHTML  =  "Hay nhap ma dung";
}


//function ShowHintCTTK(q,aDataLoaiTK, aDataDV, aDataCP, txtMa, ngandong )
function zExitMaCTTK(id, aDataLoaiTK, aDataDV, aDataCP)
{

	currentid = id;
	var x=document.getElementById(id);
	x = x.parentNode;
	var a = x.getElementsByTagName('div')[0];

	var stk, astk, pos;
	var kq = document.getElementById(id).value.toUpperCase();

	/// loai tai khoan:
	//lay tai khoan du:
	var idmatk = id.replace("chitiettkdu", "tkdu");
	var idmatk_value =document.getElementById(idmatk).value;

	if (idmatk_value.length == 0)
	{
		document.getElementById(txtMa).value = "";
		//document.getElementById(idmatk).focus();
		a.innerHTML= "";
		return;
	}

	/// lay danh muc tuong ung
	dmtkLoai = aDataLoaiTK.split(",");
	var inpos = dmtkLoai.indexOf(idmatk_value+"-DV");
	if (inpos>=0)
	{
		aDataDV = aDataDV.replace(sbold, "");
		aDataDV = aDataDV.replace(ebold, "");
		dmtk = aDataDV.split(",");
	}
	else 
	{
		inpos = dmtkLoai.indexOf(idmatk_value+"-CP");
		if (inpos>=0)
		{
			aDataCP = aDataCP.replace(sbold, "");
			aDataCP = aDataCP.replace(ebold, "");
			dmtk = aDataCP.split(",");
		}
		else
		{
			document.getElementById(txtMa).value = "";
			//document.getElementById(idsotienvn).focus();
			a.innerHTML= "";
			return;

		}

	}
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toUpperCase();
		pos = stk.indexOf(kq);
		if (pos==0)
		{
			astk = stk.split("-");
			document.getElementById(id).value = astk[0];
			//document.getElementById(idHint).innerHTML  =  astk[1];
			a.innerHTML  =  astk[1].toLowerCase();;
			return;
		}
	}

	alert("Hay nhap ma dung");
	document.getElementById(id).value = kq;
	document.getElementById(id).focus();
	//document.getElementById(idHint).innerHTML  =  "Hay nhap ma dung";
	a.innerHTML  =  "Hay nhap ma dung";

}

function getMA(q, txtMa, txtHint)
{
	var subdata = q.split("-");

	document.getElementById(txtMa).value=subdata[0];
	document.getElementById(txtHint).innerHTML=subdata[1];

}

function testFieldNumber(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field)) {
      // Case of error
      field.value = "";
    }
}

function UpdateRecord(host, username, password, databaseName, year, urlupdate  )
  {
	  var matk=document.getElementById('matk').value;
	  var mant=document.getElementById('mant').value;
	  var madv = document.getElementById('madv').value;
	  var dknont = document.getElementById('dknont').value;
	  var dknovn = document.getElementById('dknovn').value;
      jQuery.ajax({
       type: "POST",
       url: urlupdate,
	   data: {host: host, username: username, password: password, databaseName: databaseName, year: year, matk:matk },
       cache: false,
       success: function(response)
       {
		
         alert("Ghi xong!");

       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
  }




function PrintCT(idphieu, nam, noco, url)
{
	url = url+"?idphieu="+idphieu+"&&noco="+noco+"&&nam="+nam;
	var win = window.open(url, '_blank');
}

function PrintCT_CE(idphieu, nam, noco, url)
{
	if (idphieu=="")
	{
  		idphieu = $('div#idphieu').html();
		idphieu = idphieu.trim();
	}

	url = url+"?idphieu="+idphieu+"&&noco="+noco+"&&nam="+nam;
	var win = window.open(url, '_blank');
}

function isValidDate3(d) {
	if ( Object.prototype.toString.call(d) === "[object Date]" ) {
	  if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
		return false;
	  }
	  else {
		return true;
	  }
	}
	else {
		return false;
	}
}


function validdate(nStr) {

}

function isValidDate(y, m, d) {
	if (m>12 || m<1)
	{
		alert("Nhập tháng không đúng!");
		return false;
	}


	switch (m)
	{
	   case 1:
	   case 3:
	   case 5: 
	   case 7: 
	   case 8: 
	   case 10: 
	   case 12: 
		   if (d>0 && d<32 )
		   {
			return true;
		   }
		   break;

	   case 4:
	   case 6:
	   case 9: 
	   case 11: 
		   if (d>0 && d<31 )
		   {
			return true;
		   }
		   break;
	  case 2:
		   if (d>0 && d<29 )
		   {
			return true;
		   }
		   break;

	   default: 
		   alert('Nhập ngày không đúng');
			return false;

	}
	return false;


}


function InsCTTMTG(pnew, url, journalid,  year, mant, matk, mact, noco, urlupdate, urlmain )
{
	 if ($("input#save").val() == "Thêm mới")
	 {
  		 ChangeTT("Thêm");
		 ngct = $('input#ngct').val();
		 ngaylapct = $('input#ngaylapct').val();
		 ngaylapct = $('input#ngayctcn').val();
		 ma_dk  = $('input#ma_dk').val();
		 ma_dvcs = $('div#ttma_dvcs').html();
		 tk = $('select#tk').val();
		 mant = $('select#mant').val();
		// phần chi tiết
		 var x=document.getElementById('myDetail');
		 var a = x.getElementsByTagName('a');
		 var sda = a.length ;
		 sd = sda - SODONGCT;0
		 // Xoa bot cac dong thua
		 for (i=0 ;i<sd ; i++){
			document.getElementById("myDetail").deleteRow(ndongbd+1);
		 }
		 // them cac dong con thieu
		 sd = SODONGCT - sda ;
		 for (i=0 ;i<sd ; i++){
			  addnewrow_add();
		 }
		  
 		// phần thuế
		 var x=document.getElementById('myDetailThue');
		 var a = x.getElementsByTagName('a');
		 var sda = a.length ;
		 sd = sda - SODONGCT;
		 // Xoa bot cac dong thua
		 for (i=0 ;i<sd ; i++){
			document.getElementById("myDetail").deleteRow(ndongbd+1);
		 }
		 // them cac dong con thieu
		 sd = SODONGCT - sda ;
		 for (i=0 ;i<sd ; i++){
			  addnewrow_add();
		 }
		 // End phần thuế
	

		 $('input:text').val("");
		 $('select').val(0);
		 $('select#tk').val(tk);
		 $('select#mant').val(mant);

		 $('input#ngct').val(ngct);
		 $('input#ngaylapct').val(ngaylapct);
		 $('input#ngayctcn').val(ngayctcn);
		 $('input#ma_dk').val(ma_dk);
		 $('input#ma_dvcs').val(ma_dvcs);
		 $('div.selectMenu').html("");
		 $('div#idphieu').html("");
		 if ($('select#mant').val() == "VND")
		 {
			 hideusd();
		 }
		 else
		 {
			 showusd();
		 }


		 document.getElementById("total").innerHTML = "";
		 $('input#soct').focus();
		 return;
	 }

	if (pnew == 'new')
	{
		var win = window.open(url, '_blank');
	}

	var dataMain = Array();
	var fieldMain = Array();
	var dataCT = Array();
	var fieldCT = Array();
	var cot = 0;
	var cotCT = 0;
	var i;


	 //---------nhat-------------
    var dataThue = Array();
    var fieldThue = Array();
    //---------end-------------

	// kiem tra ngay chung tu
	var ngct=document.getElementById('ngct').value;
	var dt1   = parseInt(ngct.substring(0,2));
	var mon1  = parseInt(ngct.substring(3,5));
	var yr1   = parseInt(ngct.substring(6,10));
	if (yr1 != year)
	{
		alert("Ban nhap nam chua dung!");
		document.getElementById('ngct').focus();
		return;
	}
	//var ngay = yr1+"/"+ mon1+"/" + dt1;
	var ngay = dt1+"/"+ mon1+"/" + yr1;
	var test = isValidDate(dt1, mon1, yr1);
	if (test== "false")
	{
		return;
	}


	$("#mymain").each(function(i, v){
		$(this).find('select').each(function(ii, vv){
			giatri = $("option:selected", this).text();
			//field = $("option:selected", this).name();
			giatri = giatri.split("::");
			dataMain[cot] = String(giatri[0]);
			fieldMain[cot] = vv.id;
			//alert(fieldMain[cot]+"="+ dataMain[cot]);
			cot = cot+1;

		});

		$(this).find('input').each(function(ii, vv){
			//alert(vv.id);
			fieldMain[cot] = vv.id;
			if (fieldMain[cot].indexOf("sotien") ==0)
			{
				var st = $(this).val();
				var st1 = parseFloat(st.replace(/,/g, ""));
				if (!isNaN(st1))
				{
					dataMain[cot] = st1;
				}
				else
				{
					dataMain[cot] = "";
				}
			}
			else
			{
				dataMain[cot]= $(this).val();
			}
			cot = cot+1;


		}); 
	})
	// xong phan main

	cot = 0;
	$(".myheaderrow").each(function(i, v){
		$(this).find('th#select').each(function(ii, vv){
			fieldCT[cot] = $(this).attr("name");
			cot = cot+1;
		}); 
		$(this).find('th#input').each(function(ii, vv){
			fieldCT[cot] = $(this).attr("name");
			//alert(fieldCT[cot]);
			cot = cot+1;
		}); 
	})


	$(".mydatarow").each(function(i, v){
		cot = 0;
		dataCT[i] = Array();
		$(this).find('select').each(function(ii, vv){
			giatri = $("option:selected", this).text();
			giatri = giatri.split("::");
			dataCT[i][cot] = String(giatri[0]);
			cot = cot +1;
		});


		$(this).find('input').each(function(ii, vv){
			if (fieldCT[cot].indexOf("sotien") ==0)
			{
				var st = $(this).val();
				var st1 = parseFloat(st.replace(/,/g, ""));
				if (!isNaN(st1))
				{
					dataCT[i][cot] = st1;
				}
				else
				{
					dataCT[i][cot] = "";
				}
				cot = cot+1;
			}
			else
			{
				dataCT[i][cot] = $(this).val();
				//alert(i+""+ dataCT[i][cot]);
				cot = cot+1;
			}
		}); 
	})

    //-------------nhat----------------------------
    cot = 0;
    $(".myheaderrowthue").each(function(i, v){
        $(this).find('th#select').each(function(ii, vv){
            fieldThue[cot] = $(this).attr("name");
            cot = cot+1;
        });
        $(this).find('th#input').each(function(ii, vv){
            fieldThue[cot] = $(this).attr("name");
            cot = cot+1;
        });
    })
    $(".mydatarowthue").each(function(i, v){
        cot = 0;
        dataThue[i] = Array();
        $(this).find('select').each(function(ii, vv){
            giatri = $("option:selected", this).text();
            giatri = giatri.split("::");
            dataThue[i][cot] = String(giatri[0]);
            cot = cot +1;
        });
        $(this).find('input').each(function(ii, vv){
            if (fieldThue[cot].indexOf("sotien") ==0)
            {
                var st = $(this).val();
                var st1 = parseFloat(st.replace(/,/g, ""));
                if (!isNaN(st1))
                {
                    dataThue[i][cot] = st1;
                }
                else
                {
                    dataThue[i][cot] = "";
                }
                cot = cot+1;
            }
            else
            {
                dataThue[i][cot] = $(this).val();
                cot = cot+1;
            }
        });
    })
    //-------------end-----------------------------


	idphieu = $('div#idphieu').html();
	if (idphieu)
	{
		addmode="edit";
	}
	else{
		addmode="add";
	} 
	alert (addmode); 
	jQuery.ajax({
       type: "POST",
       url: urlupdate,
	   data: {journalid:journalid,  year:year,  dataMain: dataMain, fieldMain: fieldMain, dataCT: dataCT, fieldCT: fieldCT,dataThue: dataThue, fieldThue: fieldThue, mact:mact, noco:noco, idphieu: idphieu, addmode: addmode},
       cache: false,
       success: function(response)
       {
		  alert(response);
		 if (response.substring(0,1) == "2")
		 {
			 alert("Khong co du lieu!");
		 }
		 else if (response.substring(0,1) == "1")
		 {
			 alert("Co loi du lieu, mau tin khong ghi duoc!");

		 }
		 else 
		   {
			 if (idphieu == "")
			 {
	 		     var kq = response.split(":::");
				 $('div#idphieu').html(kq[1]);
				 $('input#print').attr("disabled", false);
				 $('div#ctlinks').hide();
				 $('input#save').attr("value", "Thêm mới");
			 }
			 else
			   {				
				
		       }
			$('div#action').html("Xem chứng từ");
			 $('div#ctlinks').show();
			$('input#save').attr("value", "Thêm mới");
			$('input#edit').attr("disabled", false);
			$('input#edit').attr("value", "Sửa");
			$('input#print').attr("disabled", false);


		   }
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
	return;

  }

function Edit_1CT(){
	 
	editmode = $('input#edit').val();
	idphieu = $('div#idphieu').html();
	if (idphieu = ""){
			$('input#save').attr("value", "Ghi lại");
			$('input#edit').attr("disableb", true);
			$('div#action').html("Thêm chứng từ");
		}else 
		if (editmode == "Sửa"){
			$('input#save').attr("value", "Ghi lại");
			$('input#edit').attr("value", "Thôi sửa");
			$('div#action').html("Sửa chứng từ");
			addmode = "edit";
		}
		else
		{
			$('input#save').attr("value", "Thêm mới");
			$('input#edit').attr("value", "Sửa");
			$('div#action').html("Xem chứng từ");
		}
}


function editCT(idPhieu, url)
{
	url = url + "&idPhieu=" + encodeURIComponent(idPhieu);
	location.href = url;
	//var win = window.open(url, '_blank');

}

function ThemCT(url){
	var ChiTiet = $('input[name=ChiTiet]:checked').val()
	location.href = url+"&&ChiTiet="+ChiTiet;
}


function refurl(url)
{
	location.href = url;

}

function deleCT(idphieu, soct, url, urlR)
{
	if (!(confirm("Ban muon xoa chung tu"+ soct+"  khong?")))
	{
		return;
	}

	jQuery.ajax({
		   type: "POST",
		   url: url,
		   data: {idphieu: idphieu},
		   cache: false,
		   success: function(response)
		   {
			   location.href = urlR;
		   },
		   error: function(data, errorThrown)
		  {
			  alert('request failed :'+errorThrown);
		  }
	 });
	return;

}

